package com.cmpe.group6.storyroad;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

public class MyTabsListener<T extends Fragment> implements
		ActionBar.TabListener {
	private Fragment mFragment;
	private final FragmentActivity mActivity;
	private final String mTag;
	private final Class<T> mClass;
	private android.support.v4.app.FragmentTransaction fft;

	/**
	 * Constructor used each time a new tab is created.
	 * 
	 * @param activity
	 *            The host Activity, used to instantiate the fragment
	 * @param tag
	 *            The identifier tag for the fragment
	 * @param clz
	 *            The fragment's Class, used to instantiate the fragment
	 */
	public MyTabsListener(FragmentActivity activity, String tag, Class<T> clz) {
		mActivity = activity;
		mTag = tag;
		mClass = clz;
	}

	/* The following are each of the ActionBar.TabListener callbacks */

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(
				mTag);
		fft = mActivity.getSupportFragmentManager().beginTransaction();

		if (mFragment == null) {

			// If not, instantiate and add it to the activity
			mFragment = Fragment.instantiate(mActivity, mClass.getName());
			fft.add(R.id.pager, mFragment, mTag);
			// fft.add(android.R.id.content, mFragment, mTag);
			fft.commit();
			mActivity.getSupportFragmentManager().executePendingTransactions();
		} else {

			// If it exists, simply attach it in order to show it
			fft.attach(mFragment);
			fft.commit();
			mActivity.getSupportFragmentManager().executePendingTransactions();
		}

	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {

		mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(
				mTag);

		if (mFragment != null && !mFragment.isDetached()) {
			fft = mActivity.getSupportFragmentManager().beginTransaction();
			fft.detach(mFragment);
			fft.commit();
			mActivity.getSupportFragmentManager().executePendingTransactions();
		}

	}

}
